package service

import (
	"github.com/gin-gonic/gin"
	"cookbook-go/dto"
	"strconv"
	"io/ioutil"
)

func InitElasticService(url string) *ElasticService {
	return &ElasticService{
		//dto: dto.Init("http://119.29.116.62:9200"),
		dto: dto.Init(url),
	}
}

type ElasticService struct {
	dto *dto.ElasticDto
}

func (it *ElasticService) GetLatestByPage(c *gin.Context) []byte {
	from := c.Query("from")
	fromI, _ := strconv.Atoi(from)
	size := c.DefaultQuery("size", "6")
	sizeI, _ := strconv.Atoi(size)
	return it.dto.GetLatestByPage(fromI, sizeI)
}

func (it *ElasticService) GetHotestByPage(c *gin.Context) []byte {
	from := c.Query("from")
	fromI, _ := strconv.Atoi(from)
	size := c.DefaultQuery("size", "6")
	sizeI, _ := strconv.Atoi(size)
	return it.dto.GetHotestByPage(fromI, sizeI)
}

func (it *ElasticService) GetCoursels(c *gin.Context) []byte {
	return it.dto.GetCoursels()
}

func (it *ElasticService) GetByCategory(c *gin.Context) []byte {
	cateType := c.Query("type")
	sortType := c.Query("sortType")
	from := c.Query("from")
	fromI, _ := strconv.Atoi(from)
	size := c.DefaultQuery("size", "6")
	sizeI, _ := strconv.Atoi(size)
	return it.dto.GetByCategory(cateType, fromI, sizeI, sortType)
}

func (it *ElasticService) SearchByKeyword(c *gin.Context) []byte {
	keyword := c.Query("keyword")
	return it.dto.SearchByKeyword(keyword)
}

func (it *ElasticService) SpecialSearch(c *gin.Context) []byte {
	query := c.Query("query")
	return it.dto.SpecialSearch(query)
}

func (it *ElasticService) WordAnalyze(c *gin.Context) []byte {
	text := c.Query("text")
	return it.dto.WordAnalyze(text)
}

func (it *ElasticService) ProxyQuery(c *gin.Context) []byte {
	bytes, _ := ioutil.ReadAll(c.Request.Body)
	return it.dto.ProxyQuery(bytes)
}

func (it *ElasticService) GetOneById(c *gin.Context) []byte {
	id := c.Query("id")
	return it.dto.GetOneById(id)
}
